import { Scen } from '../../types/scen'
import { execute, select } from '../../utils/db'
import { Page, PageReq } from '../../types/page'

export class ScenDao {
  /**
   * 创建场景
   */
  static async create(scen: Omit<Scen, 'id'>): Promise<number | undefined> {
    const result = await execute(
      'INSERT INTO scens (code, name, icon) VALUES (?, ?, ?) RETURNING id',
      [scen.code, scen.name, scen.icon]
    )
    return result?.lastInsertId
  }

  /**
   * 更新场景信息
   */
  static async update(id: number, scen: Partial<Scen>): Promise<void> {
    const fields = []
    const values = []

    if (scen.code) {
      fields.push('code = ?')
      values.push(scen.code)
    }
    if (scen.name) {
      fields.push('name = ?')
      values.push(scen.name)
    }
    if (scen.icon) {
      fields.push('icon = ?')
      values.push(scen.icon)
    }

    if (fields.length === 0) return

    await execute(
      `UPDATE scens SET ${fields.join(', ')} WHERE id = ?`,
      [...values, id]
    )
  }

  /**
   * 删除场景
   */
  static async delete(id: number): Promise<void> {
    await execute('DELETE FROM scens WHERE id = ?', [id])
  }

  /**
   * 获取场景详情
   */
  static async getById(id: number): Promise<Scen> {
    const result = await select<Scen>(
      'SELECT * FROM scens WHERE id = ? LIMIT 1',
      [id]
    )
    return result[0]
  }

  /**
   * 获取场景列表
   */
  static async list(): Promise<Scen[]> {
    const result = await select<Scen[]>('SELECT * FROM scens')
    return result
  }

  /**
   * 分页查询场景列表
   */
  static async page(params: PageReq<Scen>): Promise<Page<Scen>> {
    const { pageNum, pageSize } = params
    const offset = (pageNum - 1) * pageSize
    const fields = []
    const values = []
    const scen = params.params
    
    if (scen.code) {
      fields.push('code LIKE ?')
      values.push(`%${scen.code}%`)
    }
    if (scen.name) {
      fields.push('name LIKE ?')
      values.push(`%${scen.name}%`)
    }

    const condition = fields.length > 0 ? `WHERE ${fields.join(' AND ')}` : ''
    const [totalResult, listResult] = await Promise.all([
      select('SELECT COUNT(*) as count FROM scens ' + condition, values),
      select<Scen[]>(`SELECT * FROM scens ${condition} LIMIT ${pageSize} OFFSET ${offset}`, values)
    ])
  //  console.log(totalResult)
  //  console.log(listResult)
    return {
      total: totalResult[0].count,
      list: (listResult as unknown as Scen[]) || []
    }
  }
}